﻿using System.Diagnostics;
using System;
using DataManageSystem.Data;
using DataManageSystem.Common;
using DataManageSystem.Models.Dto;
using DataManageSystem.Models;
using DataManageSystem.Exceptions;
using System.Linq;
using Minio.Exceptions;

namespace DataManageSystem.Services
{
    public class ScriptService
    {
        private readonly ApplicationDbContext _context;

        public ScriptService(ApplicationDbContext context)
        {
            _context = context;
        }

        public Result selectScriptData(int pageNum, int pageSize, string name, string description)
        {
            var query = _context.Scripts.AsQueryable();
            if (!string.IsNullOrEmpty(name))
            {
                query = query.Where(u => u.Name.Contains(name));
            }
            if (!string.IsNullOrEmpty(description))
            {
                query = query.Where(u => u.Description.Contains(description));
            }

            int total = query.Count(); // 获取总记录数

            var scripts = query
                .OrderByDescending(u => u.Id)
                .Skip((pageNum - 1) * pageSize)
                .Take(pageSize)
                .ToList();
            return Result.Success(scripts, total);
        }

        public void update(Script script)
        {
            _context.Scripts.Update(script);
            _context.SaveChangesAsync();
        }




        public void Add(Script script)
        {
            _context.Scripts.Add(script);
            _context.SaveChanges();
        }

        public void Delete(int id)
        {
            var script = _context.Scripts.FirstOrDefault(m => m.Id == id);
            if (script != null)
            {
                _context.Scripts.Remove(script);
                _context.SaveChanges();
            }
            else
            {
                throw new ServiceException("脚本不存在");
            }
        }


        public bool start(int id)
        {
            var script = _context.Scripts.FirstOrDefault(m => m.Id == id);
            if (script == null) return false;

            // 校验 IsRunning 状态下，进程是否还存在（防止数据库状态脏了）
            if (script.IsRunning && script.ProcessId.HasValue)
            {
                try
                {
                    var existingProcess = Process.GetProcessById(script.ProcessId.Value);
                    if (!existingProcess.HasExited)
                    {
                        // 已经运行
                        return false;
                    }
                    else
                    {
                        // 已退出，清理状态
                        script.IsRunning = false;
                        script.ProcessId = null;
                        _context.SaveChanges();
                    }
                }
                catch (ArgumentException)
                {
                    // 进程不存在，更新状态
                    script.IsRunning = false;
                    script.ProcessId = null;
                    _context.SaveChanges();
                }
            }

            // 启动脚本，独立的控制台窗口
            var process = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    FileName = "cmd.exe",
                    Arguments = $"/c \"{script.Path}\"",  // 运行的命令行参数
                    CreateNoWindow = false,  // 显示控制台窗口
                    UseShellExecute = true   // 使用系统外壳启动，确保命令行窗口显示
                }
            };

            var started = process.Start();

            if (started)
            {
                script.IsRunning = true;
                script.ProcessId = process.Id;
                _context.SaveChanges();
            }

            return started;
        }



        public bool stop(int id)
        {
            var script = _context.Scripts.FirstOrDefault(m => m.Id == id);
            if (script == null || !script.IsRunning || script.ProcessId == null)
                return false;

            try
            {
                // 获取进程实例
                var process = Process.GetProcessById(script.ProcessId.Value);

                // 确保进程还在运行
                if (!process.HasExited)
                {
                    // 使用 taskkill 强制终止进程，/F 强制结束
                    var taskkill = new ProcessStartInfo("taskkill", $"/F /T /PID {script.ProcessId}")
                    {
                        CreateNoWindow = true,
                        UseShellExecute = false
                    };

                    Process.Start(taskkill);  // 启动 taskkill 命令
                }
            }
            catch (ArgumentException)
            {
                // 进程不存在，忽略
            }
            catch (AccessDeniedException)
            {
                // 权限拒绝，输出提示
                Console.WriteLine("权限不足，无法终止进程！");
                return false;
            }
            catch (Exception ex)
            {
                // 捕获其他所有异常
                Console.WriteLine($"停止进程时出现问题: {ex.Message}");
                return false;
            }

            // 更新数据库状态，标记脚本为未运行
            script.IsRunning = false;
            script.ProcessId = null;
            _context.SaveChanges();

            return true;
        }




    }
}
